package com.jl.core.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.jl.config.BaseResponse;
import com.jl.core.common.WxConstants;
import com.jl.core.util.file.FileUtil;
import com.jl.model.User;
import com.jl.service.AuthService;
import com.jl.service.GetUserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 登录权限
 */
@Controller
@RequestMapping("authentication")
@Slf4j
@Api(description = "登录校验")
public class AuthenticationController {

    @Autowired
    private WxConstants wxConstants;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private AuthService authService;
    @Autowired
    private GetUserInfoService getUserInfoService;

//    @GetMapping("/wx/login")
//    @ApiOperation(value = "登录")
//    public void wxLogin(HttpServletResponse response){
//        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxConstants.getAppId() +
//                "&redirect_uri=" + wxConstants.getRedirectUrl() +
//                "&response_type=code" +
//                "&scope=" + wxConstants.getScope()+
//                "&state=STATE#wechat_redirect";
//        try {
//            response.sendRedirect(url);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    @GetMapping("/wx/login")
    @ApiOperation(value = "登录")
    @ResponseBody
    public BaseResponse wxCallback(String code, HttpServletResponse response){
//        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxConstants.getAppId() +
//                "&secret=" + wxConstants.getAppSecret() +
//                "&code=" + code +
//                "&grant_type=authorization_code";
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxConstants.getAppId() + "&secret="
                + wxConstants.getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = JSONObject.parseObject(HttpUtil.get(url));
        String openId = jsonObject.getString("openid");
        String accessToken = jsonObject.getString("access_token");
        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken +
                "&openid=" + openId +
                "&lang=zh_CN";
        String userInfoJson = HttpUtil.get(url);
//        userInfoJson = "{\"openid\":\"oA6fMwy_ppXuWFWz0pbZoGkSA51M\",\"nickname\":\"点神科技测试号\",\"sex\":0,\"language\":\"zh_CN\",\"city\":\"\",\"province\":\"\",\"country\":\"\",\"headimgurl\":\"http://thirdwx.qlogo.cn/mmopen/vi_32/zWCuuOtLUz1zGovjKQUdqtmlyD7CQ7gp9hBIsqotYzZxP97fTTyx135bzDiaoDwEAvlwwWeNhicek9IAv8icYgr6A/132\",\"privilege\":[],\"unionid\":\"oBMYU1N2pAizC0uz4pW60F_fxkGU\"}";
        //保存到数据库
        JSONObject jsonObject1 = JSONObject.parseObject(userInfoJson);
        String headImgUrl = FileUtil.savePhoto(jsonObject1.getString("headimgurl"));
        User user = new User(jsonObject1.getString("openid"),jsonObject1.getString("nickname"),jsonObject1.getString("sex"),jsonObject1.getString("province"),
                jsonObject1.getString("city"),jsonObject1.getString("country"),headImgUrl,jsonObject1.getString("unionid"));
        User userInfo = authService.insertUser(user);
        user.setPhone(userInfo.getPhone());
        user.setCoin(userInfo.getCoin());
        //保存接口调用TOKEN
        String token1 = getUserInfoService.setUserToken(String.valueOf(userInfo.getId()));
        //保存到redis
        getUserInfoService.setUserToRedis(user);
        //保存accessToken
        String token = userInfo.getId()+"_accessToken";
        String s = redisTemplate.opsForValue().get(token);
        if (StringUtils.isEmpty(s)){
            redisTemplate.opsForValue().set(token,accessToken,2,TimeUnit.HOURS);
        }
        //保存用户账户信息到redis
        getUserInfoService.setUserRealTime(userInfo);
        return BaseResponse.success(token1);
    }

    /*
    手机登录
     */
    @GetMapping("/phone/login")
    @ApiOperation(value = "手机登录")
    @ResponseBody
    public BaseResponse phoneLogin(String phone, String password){
        User user = authService.phoneLogin(phone, password);
        if (user==null){
            return BaseResponse.error("501","手机号或密码错误");
        }
        //保存到redis
        getUserInfoService.setUserToRedis(user);
        //保存接口调用TOKEN
        String token = getUserInfoService.setUserToken(String.valueOf(user.getId()));
        //保存用户账户信息到redis
        getUserInfoService.setUserRealTime(user);
        return BaseResponse.success(token);
    }

}
